//
//  HomeTableViewController.swift
//  XNWeiBo_Swift
//
//  Created by xunan on 16/6/18.
//  Copyright © 2016年 xunan. All rights reserved.
//

import UIKit
import SVProgressHUD

let XMGHomeReuseIdentifier = "XMGHomeReuseIdentifier"
class HomeTableViewController: BaseTableViewController {
    
    
    var statuses: [Status]? {
        didSet {
            tableView.reloadData()
        }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !userLogin {
            visitorView?.setupVisitorInfo(true, imageName: "visitordiscover_feed_image_house", message: "关注一些人,回到这里看看有什么惊喜")
            return
        }
        // 初始化导航条
        setupNav()
        
        // 注册通知
        NSNotificationCenter.defaultCenter() .addObserver(self, selector: #selector(HomeTableViewController.change), name: XMGPopoverAnimatorWillShow, object: nil)
        NSNotificationCenter.defaultCenter() .addObserver(self, selector: #selector(HomeTableViewController.change), name: XMGPopoverAnimatorWillDismess, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "showPhotoBrowser:", name:XMGStatusPictureViewSelected, object: nil)
        
        tableView.registerClass(StatusNormalTableViewCell.self, forCellReuseIdentifier: StatusTableViewCellIdentifier.NormallCell.rawValue)
        tableView.registerClass(StatusForwardTableViewCell.self, forCellReuseIdentifier: StatusTableViewCellIdentifier.ForwardCell.rawValue)

        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
       
        refreshControl = HomeRefreshControl()
        refreshControl!.addTarget(self, action:#selector(loadData), forControlEvents:.ValueChanged)

        loadData()
    }
    
    /**
     显示图片浏览器
     */
    func showPhotoBrowser(notify: NSNotification)
    {
        // 注意: 如果通过通知传递数据, 一定要判断数据是否存在
        guard let indexPath = notify.userInfo![XMGStatusPictureViewIndexKey] as? NSIndexPath else {
            print("没有indexPath")
            return
        }
        
        guard let urls = notify.userInfo![XMGStatusPictureViewURLsKey] as? [NSURL] else {
            print("没有配图")
            return
        }
        
        let vc = PhotoBrowserController(index: indexPath.item, urls: urls)
        presentViewController(vc, animated: true, completion: nil)
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    var pullupRefreshFlag = false
    
    /**
     * 如果想要调用私有方法  
     * 1.去掉private
     * 2.@objc, 当做OC方法来处理
     */
    @objc private func loadData ()
    {
        
        var since_id = statuses?.first?.id ?? 0
        
        var max_id = 0
        
        if pullupRefreshFlag {
            since_id = 0
            max_id = statuses?.last?.id ?? 0
        }
        
        Status.loadStatusses(since_id, max_id: max_id) { (models, error) in
            
            // 接收刷新
            self.refreshControl?.endRefreshing()
            
            if error != nil {
                return
            }
            
            if since_id > 0 {
                // 如果是下拉刷新, 就将获取到的数据, 拼接在原有数据的前面
                self.statuses = models! + self.statuses!
                
                // 显示刷新提醒
                self.showNewStatusCount(models?.count ?? 0)

            } else if max_id > 0 {
                // 如果是上拉加载更多, 就将数据拼接在原有数据的后面
                self.statuses = self.statuses! + models!

            }
            else {
                self.statuses = models
            }            
        };
    }
    
    private func showNewStatusCount(count: Int) {
        newStatusLabel.hidden = false
        newStatusLabel.text = (count == 0) ? "没有新数据" : "刷新到\(count)条微博数据"
        
        UIView.animateWithDuration(2, animations: { () -> Void in
            self.newStatusLabel.transform = CGAffineTransformMakeTranslation(0, self.newStatusLabel.frame.height)
            
        }) { (_) -> Void in
            UIView.animateWithDuration(2, animations: { () -> Void in
                self.newStatusLabel.transform = CGAffineTransformIdentity
                }, completion: { (_) -> Void in
                    self.newStatusLabel.hidden = true
            })
        }
    }
    
    func change() {
        let titleBtn = navigationItem.titleView as! TitleButton
        titleBtn.selected = !titleBtn.selected;
    }

    
    private func setupNav() {
            
        // command + control + E 替换
        navigationItem.rightBarButtonItem = UIBarButtonItem.createBarButtonItem("navigationbar_pop",target: self,action: #selector(HomeTableViewController.rightItemClick))
        navigationItem.leftBarButtonItem = UIBarButtonItem.createBarButtonItem("navigationbar_friendsearch",target: self,action: #selector(HomeTableViewController.leftItemClick))
        
        // 2.初始化标题按钮
        let titleBtn = TitleButton()
        titleBtn.setTitle("xunan623 ", forState: UIControlState.Normal)
        titleBtn.addTarget(self, action: #selector(HomeTableViewController.titleBtnClick), forControlEvents: UIControlEvents.TouchUpInside)
        navigationItem.titleView = titleBtn
        
    }
    
    func titleBtnClick(btn: TitleButton) {
        // 弹出菜单
        let sb = UIStoryboard(name: "PopoverViewController", bundle: nil)
        let vc = sb.instantiateInitialViewController()
        // 设置专场
        vc?.transitioningDelegate = popoverAnimator
        
        // 专场动画
        vc?.modalPresentationStyle = UIModalPresentationStyle.Custom
        presentViewController(vc!, animated: true, completion: nil)
        
        
    }

    
    func rightItemClick() {
        let sb = UIStoryboard(name: "QRCodeViewContoller", bundle: nil)
        let vc = sb.instantiateInitialViewController()
        presentViewController(vc!, animated: true, completion: nil)
    }
    
    func leftItemClick() {
        print("left")
    }
    
    //MARK: -- 懒加载
    private lazy var popoverAnimator: PopoverAnimator = {
        let pa = PopoverAnimator()
        pa.presentFrame = CGRectMake(UIScreen.mainScreen().bounds.size.width/2 - 100, 56, 200, 200)
        return pa
    }()
    
    // 刷新提醒控件
    private lazy var newStatusLabel: UILabel = {
        let label = UILabel()
        let height: CGFloat = 44
        label.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, height)
        label.backgroundColor = UIColor.orangeColor()
        label.textColor = UIColor.whiteColor()
        label.textAlignment = NSTextAlignment.Center
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
        label.hidden = true
        return label
    }()
    
    // 微博行高的缓存, 利用字典作为容器, key就是微博的id, 值对应微博的行高
    var rowCache: [Int: CGFloat] = [Int: CGFloat]()
    
    override func didReceiveMemoryWarning() {
        rowCache.removeAll()
    }
    
}

extension HomeTableViewController
{
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let status = statuses![indexPath.row]

        let cell = tableView.dequeueReusableCellWithIdentifier(StatusTableViewCellIdentifier.cellID(status), forIndexPath: indexPath) as! StatusTableViewCell
        cell.status = status
        
        // 4.判断是否滚动到最后一个cell
        let count = statuses?.count ?? 0
        if indexPath.row == (count - 1) {
            print("上拉加载更多");
            pullupRefreshFlag = true
            loadData()
        }
        
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        // 1.取出对应行的模型
        let status = statuses![indexPath.row]
        
        // 2.判断缓存中有没有
        if let height = rowCache[status.id] {
//            print("从缓存中获取")
            return height
        }
        // 3.拿到cell
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusTableViewCellIdentifier.cellID(status)) as! StatusTableViewCell
        
        // 4.拿到对应的行高
        let rowHeight = cell.rowHeight(status)
        rowCache[status.id] = rowHeight
        
        return rowHeight
    }

}


















